<template>
  <div>
    <myDivider name="巡查记录"></myDivider>

    <div>
      <el-input style="width: 250px;margin-left: 10px;" v-model="keywords" placeholder="巡查码名称/巡查人/巡查码类别"
        @keyup.enter.native="SouSuo" clearable></el-input>
      <el-date-picker @change="SouSuo" v-model="keyTime" type="daterange" range-separator="至" start-placeholder="开始日期"
        end-placeholder="结束日期">
      </el-date-picker>
      <el-select @change="SouSuo" clearable v-model="keyResidentialId" placeholder="选择小区">
        <el-option v-for="item, i in keyResidentialData" :key="i" :label="item.name" :value="item.residentialId">
        </el-option>
      </el-select>
      <el-button type="primary" style="margin-top: 20px; margin-left: 15px" @click="SouSuo">查询</el-button>
      <el-button style="margin-top: 20px; margin-left: 15px" @click="reset">重置</el-button>

      <div style="display: flex;justify-content: flex-end;">
        <el-button type="success" @click="exportCode">导出巡查记录</el-button>
      </div>
    </div>

    <div>
      <el-table :data="tableData" ref="table" @select="selectTable" @select-all="selectAllTable"
        style="width: 100%;margin-top: 50px;">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="codeName" label="巡查码名称" align="center">
        </el-table-column>
        <el-table-column prop="categoryName" label="巡查码类别" align="center">
        </el-table-column>
        <el-table-column prop="operationUserName" label="巡查人" align="center">
        </el-table-column>
        <el-table-column prop="locationName" label="巡查地点" align="center">
          <template slot-scope="scope">
            <div>
              <el-tooltip class="item" effect="dark" :content="scope.row.locationName" placement="top-start">
                <span>{{ scope.row.locationName == null || scope.row.locationName == '' ? '—' :
                  scope.row.locationName.length > 7 ?
                    "..." + scope.row.locationName.substring(scope.row.locationName.length - 7,
                      scope.row.locationName.length) : scope.row.locationName }}</span>
              </el-tooltip>
              <div style="color: red;">{{ scope.row.isEffective == 0 ? '' : '超出指定距离' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="巡查时间" align="center">
        </el-table-column>
        <el-table-column prop="residentialName" label="所属小区" align="center">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.residentialInfo" placement="top-start">
              <span>{{ scope.row.residentialName }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="areaName" label="地址">
            <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.areaName" placement="top-start">
              <span>{{ scope.row.areaName == null || scope.row.areaName == '' ? '—' :
                scope.row.areaName.length > 7 ?
                  "..." + scope.row.areaName.substring(scope.row.areaName.length - 7,
                    scope.row.areaName.length) : scope.row.areaName }}</span>
            </el-tooltip>
          </template>
</el-table-column> -->

        <el-table-column label="操作" width="100px" align="center">
          <template slot-scope="scope">
            <div class="textBtn">
              <el-row>
                <el-col class="el" :span="24">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;"
                    @click="detailClick(scope.row)">详情</span>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页器 -->
    <myPagination :total="total" :pageNum="pageNum" @PageChange="PageChange" @pageSizeChange="pageSizeChange">
    </myPagination>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data() {
    return {
      keywords: '',
      keyTime: ['', ''],
      keyResidentialId: '',
      keyResidentialData: [],
      pageNum: 1,
      pageSize: 10,
      total: 6,
      tableData: [], //表格数据
      activeArr: [],//单选的情况下，该数组记录选中的数据
      cancelArr: [], //全选的情况下，该数组记录要取消掉的数据
      exportType: '',//是全选还是单选
      logOnUser: {}
    }
  },
  async activated() {
    this.exportType = ''
    this.activeArr = []
    this.logOnUser = JSON.parse(sessionStorage.getItem('logOnUser'))
    this.getkeyResidentialData()
    this.reset()

  },
  methods: {
    async getkeyResidentialData() {
      // let user = JSON.parse(sessionStorage.getItem('logOnUser'))
      let res = await this.$api.patrol.myGetResidentialQuartersList()

      if (res.code == 200) {
        this.keyResidentialData = res.data
        console.log(this.keyResidentialData, 'this.keyResidentialData');
      } else {
        this.$message.error(res.message)
      }

    },
    detailClick(row) {
      this.$router.push('/PatrolRecordDetail?id=' + row.id)
    },

    deleteClick() {

    },
    //  总表格列表=====================================================
    exportCode() {
      if (this.exportType == 'pick' && this.activeArr.length == 0) {
        this.$message.error('请先选择数据')
        return
      }
      axios({
        method: 'post',
        url: defaultUrl + `/business/qrCodeScanHistory/exportHistoryExcel`,
        data: {
          "type": this.exportType, //全选: eliminate 手动选: pick
          "categoryId": '', //二维码类别id 非必填
          "residentialId": this.keyResidentialId, //小区id 非必填
          "searchName": this.keywords, //搜索 巡查人/二维码名称 非必填
          "startTime": this.keyTime[0], //开始时间 非必填
          "endTime": this.keyTime[1], //结束时间 非必填
          "ids": JSON.stringify(this.activeArr), //如果type是pick  ids不能为空
          "eliminateIds": JSON.stringify(this.cancelArr) //如果type为eliminate eliminateIds值如果为空则为全选 取消那个就把哪个的id放进来
        },
        headers: {
          // 在这里添加自己需要的请求头
          account: this.logOnUser.account,
          token: this.logOnUser.token,
        },
        responseType: 'blob'
      }).then(res => {
        console.log(res, 'qwdqwd')
        const url = window.URL.createObjectURL(new Blob([res.data]))
        const a = document.createElement('a')
        a.href = url
        a.setAttribute('download', '巡查记录.xlsx')
        document.body.appendChild(a)
        a.click();
        document.body.removeChild(a)
      }).catch(err => {
        console.log(err, 'qdqwd');
      }
      )
    },

    selectTable(selection, row) {
      console.log(selection, row, '单选');
      if (this.exportType != 'eliminate') {
        this.exportType = 'pick'
      }
      let haveRow = false
      selection.forEach(el => {
        if (el.id == row.id) {
          haveRow = true
        }
      })
      if (this.exportType == 'eliminate') { //多选清空下，处理  需要取消的数组
        if (haveRow) {  // 如果是点击，那么 需要取消的数组就去除掉
          this.cancelArr.forEach((el, i) => {
            if (el == row.id) {
              this.cancelArr.splice(i, 1)
            }
          })
        } else {   // 如果是去除，那么 需要取消的数组就增加
          this.cancelArr.push(row.id)
        }
      } else if (this.exportType == 'pick') {//单选清空下，处理  选中的数组
        if (haveRow) {  //新增
          this.activeArr.push(row.id)
        } else {        //去除
          this.activeArr.forEach((el, i) => {
            if (el == row.id) {
              this.activeArr.splice(i, 1)
            }
          })
        }
      }

      console.log('单选', this.exportType, this.activeArr, this.cancelArr);
    },
    selectAllTable(selection) {
      if (selection.length > 0) { //全部选中
        this.exportType = 'eliminate'
      } else { //全部取消
        this.exportType = 'pick'
      }
      this.activeArr = []
      this.cancelArr = []
    },
    pageSizeChange(e) {
      this.pageNum = 1
      this.pageSize = e
      this.getTableList()
    },
    PageChange(e) {

      this.pageNum = e
      this.getTableList()
    },
    SouSuo() {
      this.pageNum = 1
      this.getTableList()
    },
    reset() {
      this.keywords = ''
      this.keyTime = ['', '']
      this.keyResidentialId = ''
      this.pageNum = 1
      this.SouSuo()
    },
    async getTableList() {
      if (!this.keyTime) {
        this.keyTime = ['', '']
      }

      let res = await this.$api.patrol.myQrCodeScanHistoryList({
        "categoryId": '', //二维码类别id 非必填
        "residentialId": this.keyResidentialId, //小区id 非必填
        "searchName": this.keywords, //搜索 巡查人/二维码名称 非必填
        "startTime": this.keyTime[0], //开始时间 非必填
        "endTime": this.keyTime[1], //结束时间 非必填
        "pageNum": this.pageNum, //页码 非必填
        "pageSize": this.pageSize //每页数量 非必填
      })
      if (res.code == 200) {
        if (res.data.list.length == 0 && this.pageNum != 1) {
          this.pageNum = 1
          this.getTableList()
          return
        }
        this.tableData = res.data.list;
        this.total = res.data.total;

        if (this.exportType == 'pick') {
          if (this.activeArr.length > 0) {
            this.tableData.forEach((el, i) => {
              this.activeArr.forEach((ell, ii) => {
                if (el.id == ell) {
                  this.$nextTick(() => {
                    this.$refs.table.toggleRowSelection(this.tableData[i], true)
                  })
                }
              });
            })
          }
        } else if (this.exportType == 'eliminate') {
          this.$nextTick(() => {
            this.tableData.forEach((el, i) => {
              this.$refs.table.toggleRowSelection(this.tableData[i], true)
              this.cancelArr.forEach((ell, ii) => {
                if (el.id == ell) {
                  this.$refs.table.toggleRowSelection(this.tableData[i], false)
                }
              });
            })
          })
        }

      } else {
        this.$message.error(res.message)
      }

    },
    // =====================================================总表格列表
  }
}
</script>

<style lang="less" scoped>
.textBtn {
  position: relative;

  /deep/ .el-row {
    display: flex;
    justify-content: center;
  }

  .el {
    display: block;
    position: relative;

    &:nth-child(n+2) {
      &::after {
        position: absolute;
        left: -1px;
        top: 50%;
        content: '';
        width: 2px;
        transform: translateY(-50%) scale(0.5, 1);
        height: 10px;
        background-color: #aaa;
      }
    }
  }
}
</style>